<template>
  <HomeWrap>
    <el-card shadow="hover" class="detail-card">
      <!-- 上：左右结构 -->
      <el-row :gutter="24" class="top-section">
        <!-- 左侧图片 -->
        <el-col :xs="24" :sm="10" :md="10">
          <div class="image-container">
            <img
              v-if="productDetail.mainImg && !imageLoadError"
              :src="productDetail.mainImg"
              class="goods-img"
              @error="handleImageError"
            />
            <div v-else class="image-placeholder">
              <el-icon :size="48" color="#DCDFE6">
                <Picture />
              </el-icon>
              <span class="placeholder-text">暂无图片</span>
            </div>
          </div>
        </el-col>

        <!-- 右侧信息 -->
        <el-col :xs="24" :sm="14" :md="14" class="info-section">
          <div class="info-wrapper">
            <!-- 标题 -->
            <h1 class="title">{{ productDetail.title }}</h1>

            <!-- 优化后的价格区域 -->
            <div class="price-section">
              <div class="price-main">
                <span class="price-symbol">￥</span>
                <span class="price-value">{{ productDetail.price }}</span>
              </div>
              <div class="crossed-price" v-if="productDetail.crossedPrice">
                原价: ￥{{ productDetail.crossedPrice }}
              </div>
            </div>

            <!-- 购物车操作 -->
            <div class="cart-section">
              <template v-if="!added">
                <el-button
                  type="primary"
                  size="large"
                  class="add-cart-btn"
                  @click="addToCart"
                  :loading="addingToCart"
                >
                  <el-icon size="18" style="margin-right: 4px"><ShoppingCart /></el-icon>
                  加入购物车
                </el-button>
              </template>
              <template v-else>
                <div class="quantity-control">
                  <span class="quantity-label">购买数量</span>
                  <el-input-number
                    v-model="count"
                    :min="1"
                    :max="productDetail.max || 99"
                    size="large"
                    @change="updateCartQuantity"
                    class="quantity-input"
                  />
                </div>
              </template>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 下：商品详情 -->
      <div class="detail-section">
        <el-tabs v-model="activeTab" class="detail-tabs">
          <el-tab-pane label="商品详情" name="detail">
            <div class="desc" v-html="productDetail.description"></div>
          </el-tab-pane>
          <el-tab-pane label="规格参数" name="specs">
            <div class="specs-content">
              <el-descriptions :column="1" border>
                <el-descriptions-item
                  v-for="attr in productDetail.attrValueList"
                  :key="attr.pnValue"
                  :label="attr.pnValue"
                >
                  {{ attr.pvValue }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </HomeWrap>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { HomeWrap } from '@/components/HomeWrap'
import { useRoute, useRouter } from 'vue-router'
import { getProductDetail } from '@/api/product/client'
import { addCart, updateCart } from '@/api/cart/client'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, ShoppingCart, Van } from '@element-plus/icons-vue'
import Cookies from 'js-cookie'

const productDetail = ref<ProductItem>({
  skuId: 0,
  skuCode: '',
  title: '',
  description: '',
  mainImg: '',
  crossedPrice: 0,
  price: 0,
  sort: 0,
  isShowToUser: 0,
  attrValueList: [],
  max: 99
})

const route = useRoute()
const router = useRouter()
const added = ref(false)
const count = ref(1)
const addingToCart = ref(false)
const cartItemId = ref<number | null>(null)
const imageLoadError = ref(false)
const activeTab = ref('detail')

const formatAttrs = (attrValueList: { pnValue: string; pvValue: string }[] | undefined) => {
  if (!attrValueList || attrValueList.length === 0) {
    return '无属性信息'
  }
  return attrValueList.map((attr) => `${attr.pnValue}: ${attr.pvValue}`).join(' | ')
}

const handleImageError = () => {
  imageLoadError.value = true
}

const fetchProductDetail = async () => {
  try {
    const skuId = route.query.skuId || route.params.skuId
    if (!skuId) {
      console.error('缺少商品ID参数')
      return
    }
    const res = await getProductDetail(skuId)
    if (res && res.data) {
      productDetail.value = {
        ...res.data,
        max: 99
      }
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

const addToCart = async () => {
  if (!Cookies.get('user_token')) {
    try {
      await ElMessageBox.confirm('加入购物车需要登录，是否前往登录页面？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      router.push('/user-login')
    } catch {
      ElMessage.info('已取消跳转')
    }
    return
  }

  addingToCart.value = true
  try {
    const params = {
      userId: 0,
      skuId: productDetail.value.skuId,
      qty: count.value,
      remark: ''
    }
    const res = await addCart(params)
    if (res) {
      added.value = true
      ElMessage.success('已加入购物车')
      if (res.data && res.data.cartId) {
        cartItemId.value = res.data.cartId
      }
    }
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  } finally {
    addingToCart.value = false
  }
}

const updateCartQuantity = async (value: number | undefined) => {
  if (!added.value || !cartItemId.value || value === undefined) return

  try {
    const params = {
      cartId: cartItemId.value,
      qty: value,
      remark: ''
    }
    const res = await updateCart(params)
    if (res) {
      ElMessage.success('购物车数量已更新')
    }
  } catch (error) {
    console.error('更新购物车数量失败:', error)
    ElMessage.error('更新购物车数量失败')
  }
}

onMounted(() => {
  fetchProductDetail()
})

defineOptions({
  name: 'ProductDetail'
})
</script>

<style scoped>
/* 全局变量 */
:root {
  --color-primary: #409eff;
  --color-success: #67c23a;
  --color-danger: #f56c6c;
  --color-text-primary: #303133;
  --color-text-regular: #606266;
  --color-text-secondary: #909399;
  --color-border: #dcdfe6;
  --color-bg: #f5f7fa;
}

/* 卡片容器 */
.detail-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 8px;
  overflow: hidden;
}

.detail-card :deep(.el-card__body) {
  padding: 0;
}

/* 顶部区域 */
.top-section {
  padding: 24px;
  background: #fff;
}

/* 图片区域 */
.image-container {
  position: sticky;
  top: 24px;
}

.goods-img {
  width: 100%;
  height: auto;
  aspect-ratio: 1 / 1;
  object-fit: cover;
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.goods-img:hover {
  transform: scale(1.02);
}

.image-placeholder {
  width: 100%;
  aspect-ratio: 1 / 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: var(--color-bg);
  border-radius: 8px;
  gap: 8px;
}

.placeholder-text {
  font-size: 14px;
  color: var(--color-text-secondary);
}

/* 信息区域 */
.info-section {
  padding-left: 12px;
}

.info-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px; /* 增大间距 */
}

/* 标题 */
.title {
  font-size: 24px;
  font-weight: 600;
  line-height: 1.4;
  color: var(--color-text-primary);
  margin: 0;
  padding-bottom: 16px; /* 增加底部间距 */
  border-bottom: 1px solid var(--color-border);
}

.price-section {
}

.price-main {
  display: flex;
  align-items: baseline;
  gap: 4px;
  color: var(--color-danger);
  font-weight: 700;
}

.price-symbol {
  font-size: 24px;
}

.price-value {
  font-size: 48px; /* 大幅增大价格字体 */
  letter-spacing: -1px; /* 减少数字间距 */
}

.crossed-price {
  margin-top: 8px;
  font-size: 14px;
  color: var(--color-text-secondary);
  text-decoration: line-through;
}

/* 购物车区域 */
.cart-section {
  padding-top: 20px;
  border-top: 1px solid var(--color-border);
}

.add-cart-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.add-cart-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  background: var(--color-bg);
  border-radius: 8px;
}

.quantity-label {
  font-size: 14px;
  color: var(--color-text-regular);
}

.quantity-input {
  flex: 1;
}

/* 详情区域 */
.detail-section {
  background: #fff;
  border-top: 1px solid var(--color-border);
}

.detail-tabs :deep(.el-tabs__header) {
  margin: 0 24px;
  padding-top: 12px;
}

.detail-tabs :deep(.el-tabs__content) {
  padding: 24px;
}

/* 富文本描述 */
.desc {
  font-size: 14px;
  line-height: 1.8;
  color: var(--color-text-regular);
  word-break: break-word;
  padding: 0 20px;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
}

.desc :deep(p),
.desc :deep(div),
.desc :deep(h1),
.desc :deep(h2),
.desc :deep(h3),
.desc :deep(h4),
.desc :deep(h5),
.desc :deep(h6),
.desc :deep(ul),
.desc :deep(ol),
.desc :deep(li) {
  margin-left: 0 !important;
  margin-right: 0 !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
  max-width: 100% !important;
}

.desc :deep(img) {
  max-width: 100% !important;
  height: auto !important;
  display: block !important;
  margin: 16px auto !important;
  border-radius: 4px;
  object-fit: contain;
}

.desc :deep(*) {
  max-width: 100% !important;
  box-sizing: border-box;
}

.specs-content {
  padding: 0 20px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .top-section {
    padding: 16px;
  }

  .info-section {
    padding-left: 0;
    margin-top: 20px;
  }

  .title {
    font-size: 20px;
  }

  .price-value {
    font-size: 36px;
  }

  .price-symbol {
    font-size: 20px;
  }
}
</style>
